package com.hardson.toolkit.swing;

import java.awt.Dimension;

import javax.swing.JLabel;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.text.View;

import com.hardson.toolkit.util.HtmlUtil;

public abstract class WrapLabel {

	/**
	 * 将JLabel文本按照width宽度自动换行，会改变label的preferredSize为width，高度按照内容自动计算
	 *
	 * @param width
	 *            设定的换行宽度
	 * @param label
	 *            目标JLabel
	 * @return width<=0 或label为null时，返回label
	 */
	public static JLabel wrap(final int width, final JLabel label) {
		if (width <= 0 || label == null) {
			return label;
		}
		String text = HtmlUtil.htmlTag(label.getText());
		label.setText(text);
		View labelView = BasicHTML.createHTMLView(label, label.getText());
		labelView.setSize(width, 150);
		label.setPreferredSize(new Dimension(width, (int) labelView.getMinimumSpan(View.Y_AXIS)));
		return label;
	}
}
